import axios from 'axios'
import { Dialog, Toast } from 'vant'
import store from '@/store'
import router from '../route'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  // 后续接口变量直接使用VUE_APP_BASE_API即可，根据环境自动切换（process.env.VUE_APP_BASE_API）
  baseURL: import.meta.env.VITE_BASE_URL,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000 // request timeout
})
// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    config.headers.xtoken = localStorage.getItem('x-token')
    if (localStorage.getItem('userId')) {
      config.headers['User-Id'] = localStorage.getItem('userId')
    }
    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 0) {
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 401) {
        // to re-login
        console.log(store)
        Dialog.confirm({
          title: '登录失效',
          message: '登录信息已失效，点击取消停留在当前页面或者重新登录',
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.commit('app/setToken', '')
          router.replace('/login')
        })
      } else {
        Toast({
          message: res.msg || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject(new Error(res.msg || res.message || 'Error'))
    } else {
      return res
    }
  },
  (error) => {
    console.log('err:' + error) // for debug
    if (error.message === 'Network Error') {
      Toast({
        type: 'error',
        message: '访问网络不稳定，请稍后再试'
      })
      return Promise.reject(error)
    }
    if (error.message.includes('timeout')) {
      Toast({
        type: 'error',
        message: '连接服务器超时，请稍后再试'
      })
      return Promise.reject(error)
    }
    Toast({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
